import { createRouter, createWebHistory } from 'vue-router'
import { isAuthenticated } from '@/utils/auth'

// 直接导入组件，不使用懒加载
import LoginView from '../views/LoginView.vue'
import ValidationView from '../views/ValidationView.vue'
import GeneratorView from '../views/GeneratorView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/',
      name: 'validation',
      component: ValidationView,
    },
    {
      path: '/generator',
      name: 'generator',
      component: GeneratorView,
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/',
    },
  ],
})

// 路由守卫：检查登录状态和过期时间
router.beforeEach((to, from, next) => {
  const isLoggedIn = isAuthenticated()
  if (to.path === '/login') {
    // 已登录访问登录页则跳转首页
    if (isLoggedIn) return next('/')
    return next()
  }
  // 其他路由需要登录
  if (!isLoggedIn) return next('/login')
  next()
})

export default router
